<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="600px"
    :before-close="handleClose"
    class="chat-dialog"
  >
    <div class="chat-container">
      <!-- 聊天消息列表 -->
      <div class="chat-messages" ref="messagesContainer">
        <div
          v-for="message in messages"
          :key="message.id"
          class="message-item"
          :class="{ 'own-message': message.senderId === currentUserId }"
        >
          <div class="message-avatar">
            <el-avatar :size="32" :src="getAvatarUrl(message.senderId)">
              {{ getAvatarText(message.senderId) }}
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="message-header">
              <span class="sender-name">{{ getSenderName(message.senderId) }}</span>
              <span class="message-time">{{ formatTime(message.createdAt) }}</span>
            </div>
            <div class="message-body">
              <div v-if="message.messageType === 'TEXT'" class="text-message">
                {{ message.content }}
              </div>
              <div v-else-if="message.messageType === 'SERVICE_INQUIRY'" class="inquiry-message">
                <el-tag type="info" size="small">服务咨询</el-tag>
                <p>{{ message.content }}</p>
              </div>
              <div v-else-if="message.messageType === 'ORDER_INQUIRY'" class="inquiry-message">
                <el-tag type="warning" size="small">订单咨询</el-tag>
                <p>{{ message.content }}</p>
              </div>
              <div v-else class="system-message">
                {{ message.content }}
              </div>
            </div>
          </div>
        </div>
        
        <!-- 加载更多 -->
        <div v-if="hasMore" class="load-more">
          <el-button type="text" @click="loadMoreMessages" :loading="loading">
            加载更多消息
          </el-button>
        </div>
        
        <!-- 空状态 -->
        <div v-if="messages.length === 0 && !loading" class="empty-messages">
          <el-empty description="暂无聊天记录" />
        </div>
      </div>
      
      <!-- 消息输入区域 -->
      <div class="chat-input">
        <div class="input-toolbar">
          <el-button-group>
            <el-button size="small" @click="insertTemplate('您好，我想了解一下这个服务的详细信息')">
              <el-icon><ChatDotRound /></el-icon>
              常用语
            </el-button>
            <el-button size="small" @click="insertTemplate('请问有什么优惠活动吗？')">
              <el-icon><Discount /></el-icon>
              优惠
            </el-button>
            <el-button size="small" @click="insertTemplate('服务时间是怎么安排的？')">
              <el-icon><Clock /></el-icon>
              时间
            </el-button>
          </el-button-group>
        </div>
        
        <div class="input-area">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="输入消息..."
            @keydown.enter.ctrl="sendMessage"
            @keydown.enter.exact.prevent="sendMessage"
            maxlength="500"
            show-word-limit
          />
          <div class="input-actions">
            <span class="input-tip">Ctrl+Enter 发送</span>
            <el-button
              type="primary"
              @click="sendMessage"
              :loading="sending"
              :disabled="!inputMessage.trim()"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ChatDotRound, Discount, Clock } from '@element-plus/icons-vue'
import { chatApi } from '@/services/merchantService'
import { useUserStore } from '@/stores/user'
import webSocketClient from '@/utils/websocket'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  targetUserId: {
    type: String,
    required: true
  },
  targetUserName: {
    type: String,
    default: ''
  },
  serviceInfo: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'close'])

const userStore = useUserStore()
const visible = ref(false)
const messages = ref([])
const inputMessage = ref('')
const loading = ref(false)
const sending = ref(false)
const hasMore = ref(true)
const currentPage = ref(0)
const messagesContainer = ref(null)

const currentUserId = computed(() => userStore.user?.id || userStore.user?.username)
const dialogTitle = computed(() => `与 ${props.targetUserName || props.targetUserId} 的对话`)

// 监听对话框显示状态
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    loadChatHistory()
  }
})

watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
  if (!newVal) {
    emit('close')
  }
})

// 加载聊天历史
const loadChatHistory = async () => {
  if (loading.value) return
  
  loading.value = true
  try {
    const response = await chatApi.getChatHistory(props.targetUserId, {
      page: 0,
      size: 20
    })
    
    messages.value = response.data?.content || []
    hasMore.value = !response.data?.last
    currentPage.value = 0
    
    // 标记消息为已读
    await markMessagesAsRead()
    
    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  } catch (error) {
    console.error('加载聊天历史失败:', error)
    ElMessage.error('加载聊天历史失败')
  } finally {
    loading.value = false
  }
}

// 加载更多消息
const loadMoreMessages = async () => {
  if (loading.value || !hasMore.value) return
  
  loading.value = true
  try {
    const response = await chatApi.getChatHistory(props.targetUserId, {
      page: currentPage.value + 1,
      size: 20
    })
    
    const newMessages = response.data?.content || []
    messages.value = [...newMessages, ...messages.value]
    hasMore.value = !response.data?.last
    currentPage.value++
  } catch (error) {
    console.error('加载更多消息失败:', error)
    ElMessage.error('加载更多消息失败')
  } finally {
    loading.value = false
  }
}

// 发送消息
const sendMessage = async () => {
  const content = inputMessage.value.trim()
  if (!content || sending.value) return
  
  sending.value = true
  try {
    const messageData = {
      receiverId: props.targetUserId,
      content: content,
      messageType: 'TEXT'
    }
    
    // 如果有服务信息，发送服务咨询
    if (props.serviceInfo) {
      messageData.messageType = 'SERVICE_INQUIRY'
      messageData.serviceId = props.serviceInfo.id
    }
    
    const response = await chatApi.sendMessage(messageData)
    
    // 添加到消息列表
    messages.value.push(response.data)
    inputMessage.value = ''
    
    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
    
    ElMessage.success('消息发送成功')
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  } finally {
    sending.value = false
  }
}

// 插入模板消息
const insertTemplate = (template) => {
  inputMessage.value = template
}

// 标记消息为已读
const markMessagesAsRead = async () => {
  try {
    await chatApi.markAllMessagesAsReadBetween(props.targetUserId)
  } catch (error) {
    console.error('标记消息已读失败:', error)
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 获取头像URL
const getAvatarUrl = (userId) => {
  // 这里可以根据用户ID获取头像URL
  return ''
}

// 获取头像文字
const getAvatarText = (userId) => {
  return userId ? userId.charAt(0).toUpperCase() : 'U'
}

// 获取发送者名称
const getSenderName = (senderId) => {
  if (senderId === currentUserId.value) {
    return '我'
  }
  return senderId === props.targetUserId ? props.targetUserName || props.targetUserId : senderId
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 24小时内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleDateString()
  }
}

// 处理关闭
const handleClose = () => {
  visible.value = false
}

// WebSocket消息处理
const handleWebSocketMessage = (message) => {
  if (message.type === 'chat' && 
      (message.fromUserId === props.targetUserId || message.toUserId === props.targetUserId)) {
    // 添加新消息到列表
    messages.value.push({
      id: Date.now(),
      senderId: message.fromUserId,
      receiverId: message.toUserId,
      content: message.content,
      messageType: message.messageType || 'TEXT',
      createdAt: new Date().toISOString(),
      isRead: false
    })
    
    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
    
    // 标记为已读
    markMessagesAsRead()
  }
}

onMounted(() => {
  // 监听WebSocket消息
  webSocketClient.on('chat', handleWebSocketMessage)
})

onUnmounted(() => {
  // 移除WebSocket监听
  webSocketClient.off('chat', handleWebSocketMessage)
})
</script>

<style scoped>
.chat-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.chat-container {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f5f5;
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  align-items: flex-start;
}

.message-item.own-message {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 8px;
}

.message-content {
  max-width: 70%;
  background: white;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.own-message .message-content {
  background: #409eff;
  color: white;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
  font-size: 12px;
  opacity: 0.8;
}

.message-body {
  line-height: 1.5;
}

.inquiry-message {
  padding: 8px 0;
}

.inquiry-message p {
  margin: 8px 0 0 0;
}

.load-more {
  text-align: center;
  margin: 16px 0;
}

.empty-messages {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.chat-input {
  border-top: 1px solid #e4e7ed;
  background: white;
}

.input-toolbar {
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
}

.input-area {
  padding: 16px;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.input-tip {
  font-size: 12px;
  color: #999;
}
</style>
